package com.ruoyi.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.system.api.model.request.AppUserBalanceAocRequest;
import com.ruoyi.user.mapper.BalanceMapper;
import com.ruoyi.user.model.constant.UserConstant;
import com.ruoyi.user.model.pojo.entity.Balance;
import com.ruoyi.user.model.pojo.result.app.AppUserBalanceResult;
import com.ruoyi.user.service.IBalanceLogService;
import com.ruoyi.user.service.IBalanceService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户余额表 服务实现类
 * </p>
 *
 * @author Gnc
 * @since 2024-12-24
 */
@Service
public class BalanceServiceImpl extends ServiceImpl<BalanceMapper, Balance> implements IBalanceService {

    @Autowired
    private IBalanceLogService balanceLogService;

    @Autowired
    private RedissonClient redissonClient;


    @Override
    public boolean aocBalance(Long userId, Integer type, String content, Integer balType, BigDecimal money) {
        return incAndDcoBalance(userId, type, content, balType, money, true);
    }

    @Override
    public boolean aocBalanceBatch(List<AppUserBalanceAocRequest> requests, Integer type, String content, Integer balType) {
        for (AppUserBalanceAocRequest request : requests) {
            incAndDcoBalance(request.getUserId(), type, request.getRemark(), balType, request.getMoney(), true);
        }
        return true;
    }


    @Override
    public boolean docBalance(Long userId, Integer type, String content, Integer balType, BigDecimal money) {
        return incAndDcoBalance(userId, type, content, balType, money, false);
    }

    @Override
    public boolean incAndDcoBalance(Long userId, Integer type, String content, Integer balType, BigDecimal balance, boolean incOrDec) {
        RLock lock = redissonClient.getLock("balance" + userId);
        try {
            if (lock.tryLock(10, 5, TimeUnit.SECONDS)) {
                Balance one = getOne(new QueryWrapper<Balance>().lambda().eq(Balance::getUserId, userId).eq(Balance::getType, balType));
                if (one == null) {
                    one = new Balance();
                    one.setBalance(BigDecimal.valueOf(0));
                    one.setUserId(userId);
                    one.setType(balType);
                    boolean save = save(one);
                    if (!save) return false;
                }
                BigDecimal oldBalance = one.getBalance();
                if (incOrDec) { // 增加余额
                    one.setBalance(one.getBalance().add(balance));
                } else { // 扣除余额
                    one.setBalance(one.getBalance().subtract(balance));
                }
                Assert.isTrue(one.getBalance().compareTo(BigDecimal.valueOf(0)) > -1, "余额不足");
                boolean update = update(new UpdateWrapper<Balance>()
                        .lambda()
                        .eq(Balance::getBalance, oldBalance)
                        .eq(Balance::getUserId, one.getUserId())
                        .eq(Balance::getType, one.getType())
                        .set(Balance::getBalance, one.getBalance())
                );
                Assert.isTrue(update, "操作失败");
                balanceLogService.addLog(userId, type, content, balType, 0L, balance);
                return true;
            }
        } catch (InterruptedException e) {
            // 抛出异常 操作失败
            return false;
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
        return false;
    }

    @Override
    public AppUserBalanceResult balance(Long userId) {
        Balance one = lambdaQuery().eq(Balance::getUserId, userId)
                .eq(Balance::getType, UserConstant.BalanceType.balance)
                .one();
        return AppUserBalanceResult.builder()
                .balance(Optional.ofNullable(one).orElse(new Balance()).getBalance())
                .build()
                ;
    }
}
